﻿using B.S.GridManager.Api.Read.Application.Command.PhysicalGrid;
using B.S.GridManager.Api.Read.Dtos;
using B.S.GridManager.ErrorCode;
using B.S.GridManager.Infrastructure.Interface;
using B.S.GridManger.Domain.Entities;
using MediatR;

namespace B.S.GridManager.Api.Read.Application.CommandHandler.PhysicalGrid
{
    /// <summary>
    /// 查询物理网格分页列表的中介者处理类
    /// </summary>
    public class GetPhysicalGridHandler : IRequestHandler<GetPhysicalGridCommand, ApiPaging<PhysicalGridDto>>
    {
        private readonly IBaseRepository<PhysicalGridModel> physicalRepo;
        private readonly IBaseRepository<AreaModel> areaRepo;
        /// <summary>
        /// 通过构造函数注入仓储
        /// </summary>
        /// <param name="physicalRepo">物理网格仓储</param>
        /// <param name="areaRepo">区域仓储</param>
        public GetPhysicalGridHandler(IBaseRepository<PhysicalGridModel> physicalRepo, IBaseRepository<AreaModel> areaRepo)
        {
            this.physicalRepo = physicalRepo;
            this.areaRepo = areaRepo;
        }


        /// <summary>
        /// 分页查询物理网格列表的中介者处理方法
        /// </summary>
        /// <param name="request">请求命令</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>Task包装的分页响应类对象</returns>
        public Task<ApiPaging<PhysicalGridDto>> Handle(GetPhysicalGridCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<PhysicalGridDto> result = new ApiPaging<PhysicalGridDto>(); //实例化一个分页响应包装类

            var phsicals = physicalRepo.GetAll().Where(x=>!x.IsDeleted); //所有物理网格查询表达式
            var areas = areaRepo.GetAll(); //所有区域的查询表达式

            //条件查询:组合查询（含精确查询）
            if (!string.IsNullOrEmpty(request.GirdName)) {
                phsicals = phsicals.Where(x => x.GirdName.Contains(request.GirdName));
            }

            if (!string.IsNullOrEmpty(request.AreaName)) {
                areas = areas.Where(x=>x.AreaName==request.AreaName);
            }

            var linq = from p in phsicals
                       join a in areas on p.AreaId equals a.Id
                       select new PhysicalGridDto { 
                        Id = p.Id,
                        AreaId = p.AreaId,
                        AreaName = a.AreaName,
                        GridCode = p.GridCode,
                        GirdName=p.GirdName
                       };

            //分页
            result.TotalCount = linq.Count();//总条数
            result.TotalPage = (int)Math.Ceiling(result.TotalCount * 1.0 / request.PageSize);
            //分页数据
            result.Items = linq.OrderByDescending(x=>x.Id)
                     .Skip((request.PageIndex-1)*request.PageSize)
                     .Take(request.PageSize)
                     .ToList();
            result.Code = ApiEnums.Success;
            result.Msg = "查询分页数据成功";

            return Task.FromResult(result);
        }
    }
}
